import axios from "axios";
import qs from "qs";

const instance = axios.create({
  baseURL: "http://localhost:21001",
  timeout: 5000,
});

instance.interceptors.request.use(
  (config: any) => {
    const token = localStorage.getItem("t_k");

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (err) => {
    console.error(err);
  }
);

instance.interceptors.response.use(
  (response: any) => {
    //在这里判断接口异常处理逻辑
    return response.data;
  },
  (err) => {
    //在这里判断接口网络异常处理逻辑
    console.error(err);
  }
);

//创建基于restful接口规范的异步请求方法
const get = async (url: string, params: any = {}) => {
  return await instance.get(url, { params });
};
const post = async (url: string, data: any): Promise<any> => {
  return await instance.post(url, qs.stringify(data));
};
const postImg = async (url: string, data: any): Promise<any> => {
  return await instance.post(url);
};

const put = async (url: string, data: any) => {
  return await instance.put(url, qs.stringify(data));
};

const del = async (url: string, params = {}) => {
  return await instance.delete(url, { params });
};
export default {
  get,
  post,
  put,
  del,
  postImg,
};
